package com.bd.scm.module.qywx.thread;

import com.alibaba.fastjson.JSONObject;
import com.bd.scm.domain.models.qywx.TToken;
import com.bd.scm.module.qywx.init.InitServlet;
import com.bd.scm.module.utils.WxJSUtil;
import com.bd.scm.module.utils.qywx.WeiXinUtil;
import com.bd.utils.wechat.UUID;
import com.bd.utils.wechat.pojo.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Observable;

/**
 * 定时获取企业微信access_token的线程
 *
 * @author YH
 */
public class TokenThread extends Observable implements Runnable {
    private static Logger log = LoggerFactory.getLogger(TokenThread.class);

    // 第三方用户唯一凭证
    public static String corpId = "";
    // 第三方用户唯一凭证密钥
    public static String agentSecret = "";
    public static AccessToken accessToken = null;
    //企业微信JS凭证
    public static JSONObject ticketJson = null;

    // 此方法一经调用，立马可以通知观察者
    public void doBusiness(){
        if(true){
            super.setChanged();
        }
        notifyObservers();
    }

    @Override
    public void run() {
        while (true) {
            try {
                accessToken = WeiXinUtil.getAccessToken(corpId, agentSecret);
                if (null != accessToken) {
                	TToken token = new TToken();
                	token.setId(UUID.generate());
                	token.setAccessToken(accessToken.getToken());
                	token.setExpiresIn(accessToken.getExpiresIn());
                    token.setAdhibitionName("企业微信");
                    ticketJson = WxJSUtil.getQyTicketTool(accessToken.getToken());
//                	new InitServlet().saveToken(token);
                    log.info("获取企业微信access_token成功，有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getToken());
                    log.info("获取企业微信ticket成功，有效时长{}秒 token:{}", ticketJson.getString("expires_in"), ticketJson.getString("access_token"));
                    System.out.println("获取企业微信access_token成功，有效时长{"+accessToken.getExpiresIn()+"}秒 token:{"+accessToken.getToken()+"}");
                    System.out.println("获取企业微信ticket成功，有效时长{"+ticketJson.getString("ticket")+"}秒 token:{"+ticketJson.getString("expires_in")+"}");
                    // 休眠7000秒
                    Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
                } else {
                    // 如果access_token为null，60秒后再获取
                    Thread.sleep(60 * 1000);
                    log.info("获取企业微信access_token失败");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                doBusiness();
                break;
            } catch (Exception e) {
            	log.error("https request error:{}", e);
            	doBusiness();
             	break;
			}
        }
    }
}
